﻿using System;
using System.Web.Mvc;
using Matriculex.Dominio;
using Matriculex.UI.Helpers;

namespace Matriculex.UI
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
  Inherited = true, AllowMultiple = false)]
    public class AutorizexAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        private readonly Type tipoUsuario;

        public AutorizexAttribute(Type tipoUsuario)
        {
            this.tipoUsuario = tipoUsuario;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var usuario = filterContext.CurrentUser() as Usuario;
            if (usuario == null)
            {
                filterContext.Result = RedirectToLogin(filterContext);
                return;
            }

            var type = usuario.GetType();
            var accept = (type == tipoUsuario || type.IsSubclassOf(tipoUsuario));
            if (accept) return;

            filterContext.Result = RedirectToLogin(filterContext);
        }

        private static ActionResult RedirectToLogin(ControllerContext filterContext)
        {
            var redirectUrl = filterContext.HttpContext.Request.Path;
            return new RedirectResult("/Login?redir=" + redirectUrl);
        }

        //public override void OnActionExecuted(ActionExecutedContext filterContext)
        //{
        //    var result = filterContext.Result;
        //    if (!(result is ViewResult)) return;

        //    ((ViewResult)result).MasterName = masterName ?? tipoUsuario.ToString();
        //}

        //public override void OnResultExecuted(ResultExecutedContext filterContext)
        //{
        //    if (filterContext.Exception == null) return;

        //    logger.Error(filterContext.Exception.Message);
        //    filterContext.ExceptionHandled = true;
        //    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Index" }));
        //}
    }
}
